<template>
  <div class="page-content">
    <div class="header">
      <h3>招生员</h3>
    </div>
    <!-- 表格菜单 -->
    <el-tabs v-model="tableLayout" class="demo-tabs" @tab-change="handleClick" style="margin-top: 20px">
      <el-tab-pane label="驾校管理" name="1"> </el-tab-pane>
      <el-tab-pane label="车型分类" name="2"> </el-tab-pane>
      <el-tab-pane label="报名地点" name="3"> </el-tab-pane>
      <el-tab-pane label="招生员" name="4"> </el-tab-pane>
      <el-tab-pane label="教练管理" name="5"> </el-tab-pane>
      <el-tab-pane label="训练场" name="6"> </el-tab-pane>
    </el-tabs>
    <!-- 表格菜单 -->
    <el-row style="margin-top: 20px;">
      <div style="width: 12px"></div>
      <el-col :xs="24" :sm="12" :lg="6" class="el-col2">
        <el-button @click="showDialog('add')" v-ripple>新增招生员</el-button>
      </el-col>
    </el-row>

    <art-table :data="tableData" :loading="tableLoading" :currentPage="pageNum" :pageSize="pageSize" :total="pageTotal"
      @current-change="currentChange" @size-change="sizeChange">
      <template #default>
        <el-table-column label="ID" prop="id" width="55" align="center" />
        <el-table-column label="排序" prop="sortOrder" align="center" />
        <el-table-column label="联系人" prop="rsName" align="center" />
        <el-table-column label="联系电话" prop="rsPhone" align="center" />
        <el-table-column label="招生渠道" prop="recruitmentChannel" align="center">
          <template #default="{ row }">
            <span v-if="row.recruitmentChannel === '01'">线上</span>
            <span v-else-if="row.recruitmentChannel === '02'">线下</span>
          </template>
        </el-table-column>
        <el-table-column #default="scope" label="状态" align="center">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
            @click="editStatus(scope.row.id, scope.row)" />
        </el-table-column>
        <el-table-column label="创建时间：" prop="createTime" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150px" align="center">
          <template #default="scope">
            <button-table type="edit" @click="buttonMoreClick(scope.row)" />
            <button-table type="delete" @click="deleteRole(scope.row.id)" />
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增招生员' : '编辑招生员'" width="30%"
      :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="排序" prop="sortOrder">
          <el-input v-model="form.sortOrder" :rows="3" />
        </el-form-item>
        <el-form-item label="联系人" prop="rsName">
          <el-input v-model="form.rsName" />
        </el-form-item>
        <el-form-item label="联系电话" prop="rsPhone">
          <el-input v-model="form.rsPhone" />
        </el-form-item>
        <el-form-item label="招生渠道" prop="recruitmentChannel">
          <el-select v-model="form.recruitmentChannel" placeholder="请选择">
            <el-option key="01" label="线上" value="01"> </el-option>
            <el-option key="02" label="线下" value="02"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit(formRef)">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { getStudentsList, AddStudents, EditStudents, DelStudents } from '@/api/driverSchoolApi'

const dialogVisible = ref(false)
const permissionDialog = ref(false)
const tableLayout = ref('4')

const formRef = ref<FormInstance>()
const router = useRouter() // 使用useRouter获取路由实例

const rules = reactive<FormRules>({
  typename: [
    { required: true, message: '请输入报名名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  sortOrder: [{ required: true, message: '请输入正确排序', trigger: 'blur' }]
})
const tableLoading = ref(false)
const form = reactive({
  id: Number(''),
  sortOrder: 1,
  storeId: '',
  rsName: '',
  rsPhone: '',
  recruitmentChannel: '',
  status: 1
})

const tableData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
async function getData() {
  try {
    tableLoading.value = true

    const { code, data } = await getStudentsList({
      pageNum: pageNum.value,
      pageSize: pageSize.value
    })
    if (code === '00000') {
      tableData.value = data.list
      pageTotal.value = data.total
    }
  } catch (e) {
  } finally {
    tableLoading.value = false
  }
}
const currentChange = (val: number) => {
  pageNum.value = val
  getData()
}

const sizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getData()
}
const dialogType = ref('add')

const showDialog = (type: string, row?: any) => {
  dialogVisible.value = true
  dialogType.value = type
  if (type === 'edit' && row) {
    form.id = row.id
    form.status = row.status
  } else {
    form.id = Number('')
    form.rsName = ''
    form.rsPhone = ''
    form.recruitmentChannel = ''
    form.status = 1
  }
}

const buttonMoreClick = (row: any) => {
  showDialog('edit', row)
  Object.assign(form, {
    rsName: row.rsName,
    sortOrder: row.sortOrder,
    rsPhone: row.rsPhone,
    recruitmentChannel: row.recruitmentChannel
  })
}

const deleteRole = (id: number) => {
  ElMessageBox.confirm('确定删除该招生员吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(async () => {
    const res = await DelStudents(id)
    if (res.code === '00000') {
      getData()
      ElMessage.success('删除成功')
    }
  })
}

const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  try {
    const valid = await formEl.validate()
    if (!valid) return

    const isAdd = dialogType.value === 'add'
    const message = isAdd ? '新增成功' : '修改成功'
    const params = {
      storeId: parseInt(localStorage.getItem('lty-store-id') || '0'),
      sortOrder: form.sortOrder,
      rsName: form.rsName,
      rsPhone: form.rsPhone,
      recruitmentChannel: form.recruitmentChannel,
      status: form.status
    }

    let res
    if (isAdd) {
      res = await AddStudents(params)
    } else {
      res = await EditStudents(form.id, { ...params, id: form.id })
    }

    if (res.code === '00000') {
      ElMessage.success(message)
      dialogVisible.value = false
      await getData()
    }
  } catch (e) {
  }
}
interface studentParams {
  status: number
  id: number
  sortOrder: number
  rsName: string
  rsPhone: string
  recruitmentChannel: string
}
async function editStatus(id: any, params: studentParams) {
  try {
    const res = await EditStudents(id, {
      status: params.status,
      id: params.id,
      storeId: parseInt(localStorage.getItem('lty-store-id') || '0'),
      sortOrder: params.sortOrder,
      rsName: params.rsName,
      rsPhone: params.rsPhone,
      recruitmentChannel: params.recruitmentChannel
    })
    if (res.code === '0') {
    }
  } catch (e) {
  } finally {
    await getData()
  }
}

const formatDate = (date: string) => {
  return new Date(date)
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    .replace(/\//g, '-')
}

const handleClick = (e: any) => {
  console.log(e, "e===");
  if (e === '1') {
    setTimeout(() => {
      router.push('/drivingschool/DrivingschoolManagement')
    }, 0)
  } else if (e === '2') {
    setTimeout(() => {
      router.push('/drivingschool/question_bank_type')
    }, 0)
  } else if (e === '3') {
    setTimeout(() => {
      router.push('/drivingschool/question_bank_type_baoming')
    }, 0)
  } else if (e === '4') {
    setTimeout(() => {
      router.push('/drivingschool/question_bank_type_zhaosheng')
    }, 0)
  } else if (e === '5') {
    setTimeout(() => {
      router.push('/drivingschool/question_bank_type_jiaolian')
    }, 0)
  } else if (e === '6') {
    setTimeout(() => {
      router.push('/drivingschool/question_bank_type_xunlianchang')
    }, 0)
  }
}

onMounted(() => {
  getData()
})
</script>

<style lang="scss" scoped>
.page-content {
  .svg-icon {
    width: 1.8em;
    height: 1.8em;
    overflow: hidden;
    vertical-align: -8px;
    fill: currentcolor;
  }
}

.tableimg {
  width: 8rem;
  height: 4.5rem;
  border-radius: 0.5rem;
  overflow: hidden;
}
</style>
